package com.gitee.liuzhi.demo.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @Author liuzhi
 * @Date 2023/9/6 20:43
 * @Version 1.0
 * @Description SemaphoreTest
 */
@Slf4j
public class SemaphoreDemo {

    /**
     * 初始化 Semaphore 信号量为 2, 同时只允许两个线程执行
     */
    private static final Semaphore SEMAPHORE = new Semaphore(2);

    private static final Integer THREAD_COUNT = 10;

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(() -> {
                try {
                    // 申请通行证
                    SEMAPHORE.acquire();
                    // 执行业务逻辑
                    Thread.sleep(2000);
                    log.info(String.format(" %s : 处理完成", Thread.currentThread().getName()));
                    // 释放通行证
                    SEMAPHORE.release();
                } catch (InterruptedException e) {
                    log.error(String.format("thread interrupted. message:%s", e.getMessage()), e);
                }
            }).start();
        }
    }

}
